#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-08-22 01:14:23
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$


from framework.db.basedb import BaseDb
from tornado import gen
from lib.libmd5 import md5
from lib import log

class Auth(BaseDb):

    @classmethod
    def getInstance(self):
        return Auth()

    @gen.coroutine
    def get_user_auth(self, userId):
        sel_sql = '''SELECT b.Furl_id, c.Fname FROM tp_auth_url b
                    LEFT JOIN tp_url c
                    ON b.Furl_id = c.Fid
                    WHERE b.Fgroup_id =
                        (SELECT a.Fgroup_id
                        FROM tp_users a
                        WHERE a.id =%s)'''
        try:
            sel_cur = yield self.execute(sel_sql, (userId,))
            # sel_rt = sel_cur.fetchall()
            # if sel_rt != None:
            if len(sel_cur)>0:
                ret_array = []
                size = len(sel_cur)
                if size > 0:
                    for i in sel_cur:
                        ret_array.append({'authId': i[0],'authName':i[1]})
                resp = {'size':size, 'data':ret_array}
            else:
                resp = '0'
        except Exception, e:
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)

    @gen.coroutine
    def get_group(self):
        sel_sql = '''SELECT Fid,Fgroupname FROM tp_auth_group'''
        try:
            sel_cur = yield self.execute(sel_sql)
            # sel_rt = sel_cur.fetchall()
            # if sel_rt != None:
            if len(sel_cur)>0:
                ret_array = []
                size = len(sel_cur)
                if size > 0:
                    for i in sel_cur:
                        ret_array.append({'groupId': i[0],'groupName':i[1]})
                resp = {'size':size, 'data':ret_array}
            else:
                resp = '0'
        except Exception, e:
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)


    @gen.coroutine
    def new_user(self,user_name,pass_word,group_id,wx_id,realIp):
        sel_sql = '''SELECT id FROM tp_users WHERE username=%s'''
        try:
            sel_cur = yield self.execute(sel_sql, (user_name,))
            # sel_rt = sel_cur.fetchone()
            # if sel_rt != None:
            if len(sel_cur)>0:
                resp = '-2'
            else:
                ins_sql = '''INSERT INTO tp_users(Fgroup_id, username, password, Fwx_id, createip, createtime, status,csshop,gid, viptime) 
                            VALUES(%s,%s,%s,%s,%s,UNIX_TIMESTAMP(),1,1,4, UNIX_TIMESTAMP()+31287444)'''
                ins_rt = yield self.execute(ins_sql, (group_id, user_name, md5(pass_word), wx_id,realIp))
                resp = {'isok':1}
        except Exception, e:
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)


    @gen.coroutine
    def update_user(self,user_name,pass_word,group_id,realIp):
        sel_sql = '''SELECT id FROM tp_users WHERE username=%s'''
        try:
            sel_cur = yield self.execute(sel_sql, (user_name,))
            # sel_rt = sel_cur.fetchone()
            # if sel_rt == None:
            if len(sel_cur)>0:
                resp = '-2'
            else:
                upd_sql = '''UPDATE tp_users
                            SET Fgroup_id =%s
                            , password =%s
                            , createip =%s
                            WHERE username = %s'''
                upd_rt = yield self.execute(upd_sql, (group_id, md5(pass_word),realIp,user_name))
                resp = {'isok':1}
        except Exception, e:
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)

    @gen.coroutine
    def show_users(self, wx_id):
        sel_sql = '''SELECT a.id, a.username, b.Fgroupname  FROM tp_users a
                    LEFT JOIN tp_auth_group b
                    ON a.Fgroup_id = b.Fid
                    WHERE Fwx_id = %s'''
        try:
            sel_cur = yield self.execute(sel_sql, (wx_id,))
            # sel_rt = sel_cur.fetchall()
            # if sel_rt != None:
            if len(sel_cur)>0:
                ret_array = []
                size = len(sel_cur)
                if size > 0:
                    for i in sel_cur:
                        ret_array.append({'id': i[0],'userName':i[1], 'groupName':i[2]})
                resp = {'size':size, 'data':ret_array}
            else:
                resp = '0'
        except Exception, e:
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)

    @gen.coroutine
    def get_user(self, user_id):
        sel_sql = '''SELECT a.id, a.username, b.Fgroupname
                    FROM tp_users a
                    LEFT JOIN tp_auth_group b
                    ON a.Fgroup_id = b.Fid
                    WHERE id = %s'''
        try:
            sel_cur = yield self.execute(sel_sql, (user_id,))
            # sel_rt = sel_cur.fetchone()
            # if sel_rt != None:
            if len(sel_cur)>0:
                resp = {'id': sel_cur[0],'userName':sel_cur[1], 'groupName':sel_cur[2]}
            else:
                resp = '0'
        except Exception, e:
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)

    @gen.coroutine
    def del_user(self, user_name):
        sel_sql = '''SELECT id
                    FROM tp_users
                    WHERE username = %s'''
        try:
            sel_cur = yield self.execute(sel_sql, (user_name,))
            # sel_rt = sel_cur.fetchone()
            # if sel_rt ==None or sel_rt[0] == None:
            if len(sel_cur) < 1:
                resp = '0'
            else:
                del_sql = '''DELETE FROM tp_users WHERE username=%s'''
                del_cur = yield self.execute(del_sql, (user_name,))
                resp = {'isok':1}
        except Exception, e:
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)